package top.malaoshi.webmvc.parameter;

import top.malaoshi.webmvc.info.MethodsArgumentInfo;
import top.malaoshi.webmvc.exception.ParameterTypeMatchValueException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Constructor;

public class BaseTypeWrapperResolver extends AbstractResolver implements RequestParamAndMethodArgsResolver {
    @Override
    public Object resolver(HttpServletRequest request, HttpServletResponse response , MethodsArgumentInfo mai) {

        checkNameAndValue(mai);
        String parameterName = getName(mai);
        String valueStr = request.getParameter(parameterName);
        Object ret = null;
        // 如果Controlle中形参是 基本类型的包装类型，而且没有required为true，那么可以为null
        if(valueStr!=null) {
            Constructor constructor = null;
            try {
                constructor = mai.getType().getConstructor(String.class);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
            try {
                ret = constructor.newInstance(valueStr);
            } catch (Exception e) {
                // 如果valueStr为非数字字符串
                String msg = String.format("从request取出的值是[ %s ]，但形参[ %s ]类型是[ %s ]，不能赋值",
                        valueStr,mai.getName(),mai.getType().getName());
                throw new ParameterTypeMatchValueException(msg);
            }
        }
        checkRequired(ret,mai);
        return ret;
    }
}
